<?php

namespace app\api\model\kuyou\applet;

use app\api\controller\kuyou\applet\Commons;
use think\Model;
use think\Db;
use Exception;

class Writeoff extends Model
{

    // 表名
    protected $name = 'kuyou_writeoff';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = true;

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';

    /**
     * 获取列表
     * @param array $where
     * @param int $page
     * @param int $limit
     * @return array
     */
    public static function getList($where,$page,$limit,$type,$sort_field,$sort_type){
        $app_page = config('app_page');
        $app_page = $app_page===false?false:true;
        $pageStatus = true;
        if($app_page){
            if($page<0){
                $pageStatus = false;
            }
        }
        if($pageStatus){
            $list = collection(self::where(function ($query) use ($where) {
                $query->where($where);
            })->order($sort_field,$sort_type)->page($page,$limit)->field("id,purchase_code,FROM_UNIXTIME(purchase_time,'%Y-%m-%d') as purchase_time,
            business_type,customers_id,suppliers_id,write_off,preparation_id,examine_id,examine_status,print_num,remarks,
            FROM_UNIXTIME(examine_time,'%Y-%m-%d') as examine_time")->select())->toArray();
        }else{
            $list = collection(self::where(function ($query) use ($where) {
                $query->where($where);
            })->order($sort_field,$sort_type)->field("id,purchase_code,FROM_UNIXTIME(purchase_time,'%Y-%m-%d') as purchase_time,
            business_type,customers_id,suppliers_id,write_off,preparation_id,examine_id,examine_status,print_num,remarks,
            FROM_UNIXTIME(examine_time,'%Y-%m-%d') as examine_time")->select())->toArray();
        }

        foreach ($list as $list_k=>$list_v){
            $list[$list_k]['customers_name'] = (new Customers())->where(['id'=>$list_v['customers_id']])->value('customer_name');
            $list[$list_k]['suppliers_name'] = (new Suppliers())->where(['id'=>$list_v['suppliers_id']])->value('supplyer_name');
            $list[$list_k]['preparation_name'] = (new User())->where(['id'=>$list_v['preparation_id']])->value('username');
            $list[$list_k]['examine_name'] = (new User())->where(['id'=>$list_v['examine_id']])->value('username');
            unset($list[$list_k]['preparation_id']);
            unset($list[$list_k]['examine_id']);
        }
        $count = self::where(function ($query) use ($where) {
            $query->where($where);
        })->count();
        return ['list'=>$list,'count'=>$count];
    }

    /**
     * 获取详情
     * @param string $purchase_code
     * @return array
     */
    public static function getDetail($purchase_code){
        $detail = self::where(function ($query) use ($purchase_code) {
            $query->where('purchase_code', '=', $purchase_code);
        })->field("id,purchase_code,FROM_UNIXTIME(purchase_time,'%Y-%m-%d') as purchase_time,
            business_type,customers_id,customers_out_id,customers_enter_id,suppliers_id,suppliers_out_id,suppliers_enter_id,write_off,preparation_id,examine_id,examine_status,print_num,remarks,
            FROM_UNIXTIME(examine_time,'%Y-%m-%d') as examine_time")->find();
        if($detail){
            $info_list = Db::name('kuyou_writeoff_info')
                ->where(['collection_id'=>$detail['id']])
                ->select();
            foreach ($info_list as $info_list_k=>$info_list_v){
                if(!empty($info_list_v['times'])){
                    $info_list[$info_list_k]['times'] = date('Y-m-d',$info_list_v['times']);
                }
                unset($info_list[$info_list_k]['admin_id']);
                unset($info_list[$info_list_k]['old_money']);
                unset($info_list[$info_list_k]['old_status']);
            }
            $detail['info_list'] = $info_list;
        }
        if(!empty($detail)){
            return ['status'=>200,'msg'=>$detail];
        }else{
            return ['status'=>500,'msg'=>'未查询到相关数据'];
        }
    }

    /**
     * 添加
     * @param array $detail
     * @return array
     */
    public static function addDetail($detail){
        if(empty($detail)){
            return ['status'=>400,'msg'=>'参数错误'];
        }else{
            $check = (new Commons())->checkParameter($detail,[
                'purchase_code|单据编号'=>'require',
                'purchase_time|单据时间'=>'require',
                'business_type|单据类型'=>'require|in:1,2,3,4,5',
                'account_list|详细信息'=>'require',
            ]);
            if(isset($check['status'])){
                return $check;
            }else{
                $adminId = (new Commons())->getAdminId();
                if(empty($adminId)){
                    return ['status'=>410,'msg'=>'登陆无效，请重新登陆'];
                }
                $status = (new Commons())->checkCode($detail['purchase_code'],23);//验证编号是否合法
                if($status){
                    $examine= (new Commons())->getSet('examine','is_checked');

                    $account_list = isset($detail['account_list'])?$detail['account_list']:'';
                    $account = (array)json_decode($account_list, true);
                    $sale_list = isset($detail['sale_list'])?$detail['sale_list']:'';
                    $sale = (array)json_decode($sale_list, true);

                    $business_type = $detail['business_type'];
                    $info = [];
                    $log_arr = [];
                    $log_add = [];
                    $order_id = [];
                    foreach ($account as $account_k=>$account_v){
                        if(!empty($account_v['purchase_numbers']) && !empty($account_v['purchase_type'])){
                            $order = Db::name('kuyou_writeoff_source')->where(['id'=>$account_v['purchase_type']])->find();
                            if(empty($order)){
                                return ['status'=>500,'msg'=>'源单信息查询错误'];
                            }
                            if(in_array($account_v['purchase_numbers'],$order_id)){
                                return ['status'=>500,'msg'=>'不可多次选择相同的源单'];
                            }else{
                                $order_id[] = $account_v['purchase_numbers'];
                            }
                            $thisrow = [
                                'source_id'        => $order['id'],
                                'purchase_code'    => $detail['purchase_code'],
                                'purchase_time'    => strtotime($detail['purchase_time']),
                                'type'             => $order['type'],
                                'purchase_number'  => $order['purchase_code'],
                                'business_type'    => $business_type,
                                'business_name'    => isset($account_v['business_type'])?$account_v['business_type']:null,
                                'purchase_type'    => $order['purchase_type'],
                                'times'            => $order['purchase_time'],
                                'money'            => $order['price'],
                                'write_off'        => isset($account_v['write_off'])?(float)$account_v['write_off']:0,
                                'write_off_money'  => isset($account_v['write_off_money'])?(float)$account_v['write_off_money']:0,
                                'write_off_price'  => isset($account_v['write_off_price'])?(float)$account_v['write_off_price']:0,
                                'top'              => 1,
                            ];
                            $info[] = $thisrow;

                            $where = [];
                            $where['source_id'] = $order['id'];
                            $log = Db::name('kuyou_writeoff_log')->where($where)->find();
                            if($log){
                                $status = true;
                                foreach ($log_arr as $log_arr_k=>$log_arr_v){
                                    if($log_arr_v['id']==$log['id']){
                                        $status = false;
                                        $log_arr[$log_arr_k]['money'] += $thisrow['write_off_price'];
                                        $log_arr[$log_arr_k]['write_off'] -= $thisrow['write_off_price'];
                                    }
                                }
                                if($status){
                                    $log_arr[] = [
                                        'id' => $log['id'],
                                        'write_off' => $log['write_off']-$thisrow['write_off_price'],
                                        'money' => $log['money']+$thisrow['write_off_price'],
                                    ];
                                }
                            }else{
                                $log_add[] = [
                                    'source_id' => $order['id'],
                                    'write_off' => $thisrow['write_off_money']-$thisrow['write_off_price'],
                                    'money' => $thisrow['write_off_price'],
                                ];
                            }
                        }
                    }

                    $account_money = 0;
                    foreach ($info as $info_k=>$info_v){
                        $account_money += $info_v['write_off_price'];
                    }

                    $order_id = [];
                    $sale_money = 0;
                    if($business_type<=3){
                        foreach ($sale as $account_k=>$account_v){
                            if(!empty($account_v['purchase_numbers']) && !empty($account_v['purchase_type'])){
                                $sale_money += $account_v['write_off_price'];
                                $order = Db::name('kuyou_writeoff_source')->where(['id'=>$account_v['purchase_type']])->find();
                                if(empty($order)){
                                    return ['status'=>500,'msg'=>'源单信息查询错误'];
                                }
                                if(in_array($account_v['purchase_numbers'],$order_id)){
                                    return ['status'=>500,'msg'=>'不可多次选择相同的源单'];
                                }else{
                                    $order_id[] = $account_v['purchase_numbers'];
                                }
                                $thisrow = [
                                    'source_id'        => $order['id'],
                                    'purchase_code'    => $detail['purchase_code'],
                                    'purchase_time'    => strtotime($detail['purchase_time']),
                                    'type'             => $order['type'],
                                    'purchase_number'  => $order['purchase_code'],
                                    'business_type'    => $business_type,
                                    'business_name'    => isset($account_v['business_type'])?$account_v['business_type']:null,
                                    'purchase_type'    => $order['purchase_type'],
                                    'times'            => $order['purchase_time'],
                                    'money'            => $order['price'],
                                    'write_off'        => isset($account_v['write_off'])?(float)$account_v['write_off']:0,
                                    'write_off_money'  => isset($account_v['write_off_money'])?(float)$account_v['write_off_money']:0,
                                    'write_off_price'  => isset($account_v['write_off_price'])?(float)$account_v['write_off_price']:0,
                                    'top'              => 2,
                                ];
                                $info[] = $thisrow;

                                $where = [];
                                $where['source_id'] = $order['id'];
                                $log = Db::name('kuyou_writeoff_log')->where($where)->find();
                                if($log){
                                    $status = true;
                                    foreach ($log_arr as $log_arr_k=>$log_arr_v){
                                        if($log_arr_v['id']==$log['id']){
                                            $status = false;
                                            $log_arr[$log_arr_k]['money'] += $thisrow['write_off_price'];
                                            $log_arr[$log_arr_k]['write_off'] -= $thisrow['write_off_price'];
                                        }
                                    }
                                    if($status){
                                        $log_arr[] = [
                                            'id' => $log['id'],
                                            'write_off' => $log['write_off']-$thisrow['write_off_price'],
                                            'money' => $log['money']+$thisrow['write_off_price'],
                                        ];
                                    }
                                }else{
                                    $log_add[] = [
                                        'source_id' => $order['id'],
                                        'write_off' => $thisrow['write_off_money']-$thisrow['write_off_price'],
                                        'money' => $thisrow['write_off_price'],
                                    ];
                                }
                            }
                        }
                    }

                    $rowdata = [
                        'purchase_code'     =>  $detail['purchase_code'],
                        'purchase_time'     =>  strtotime($detail['purchase_time']),
                        'business_type'     =>  $detail['business_type'],
                        'customers_id'      =>  isset($detail['customers_id'])?(float)$detail['customers_id']:null,
                        'customers_out_id'  =>  isset($detail['customers_out_id'])?(float)$detail['customers_out_id']:null,
                        'customers_enter_id'=>  isset($detail['customers_enter_id'])?(float)$detail['customers_enter_id']:null,
                        'suppliers_id'      =>  isset($detail['suppliers_id'])?(float)$detail['suppliers_id']:null,
                        'suppliers_out_id'  =>  isset($detail['suppliers_out_id'])?(float)$detail['suppliers_out_id']:null,
                        'suppliers_enter_id'=>  isset($detail['suppliers_enter_id'])?(float)$detail['suppliers_enter_id']:null,
                        'write_off'         =>  $account_money,
                        'remarks'           =>  $detail['remarks'],
                        'preparation_id'    =>  $adminId,
                        'operation_id'      =>  $adminId,
                        'createtime'        =>  time(),
                        'updatetime'        =>  time(),
                    ];

                    if($account_money!=$sale_money && $business_type<=3){
                        return ['status'=>500,'msg'=>'核销金额错误'];
                    }

                    $model = new Writeoff();
                    $row = $model->where(['purchase_code'=>$detail['purchase_code']])->value('id');
                    if($row){
                        return ['status'=>500,'msg'=>'单据编号已使用，请重新输入单据编号'];
                    }
                    $result = false;
                    Db::startTrans();
                    try {
                        $model->allowField(true)->save($rowdata);
                        $result = $model->id;

                        foreach ($info as $info_k=>$info_v){
                            $info[$info_k]['collection_id'] = $result;
                        }
                        Db::name('kuyou_writeoff_info')->insertAll($info);
                        if(!empty($log_arr)){
                            (new WriteoffLog())->saveAll($log_arr);
                        }
                        if(!empty($log_add)){
                            (new WriteoffLog())->insertAll($log_add);
                        }
                        Db::commit();
                    } catch (Exception $e) {
                        Db::rollback();
                        return ['status'=>500,'msg'=>$e->getMessage()];
                    }
                    if($result){
                        if($examine!=1){
                            try {
                                $exa = self::examine($detail['purchase_code']);
                            } catch (Exception $e) {
                            }
                            if(!isset($exa['status']) || (isset($exa['status']) && $exa['status']!=1)){
                                try {
                                    self::delDetail($detail['purchase_code']);
                                } catch (Exception $e) {
                                }
                                return ['status'=>500,'msg'=>$exa['msg']];
                            }
                        }
                        return ['status'=>200,'msg'=>$detail['purchase_code']];
                    }else{
                        return ['status'=>500,'msg'=>'添加失败'];
                    }
                }else{
                    return ['status'=>500,'msg'=>'编号规则错误'];
                }
            }
        }
    }

    /**
     * 更新
     * @param array $detail
     * @return array
     */
    public static function editDetail($detail){
        if(empty($detail)){
            return ['status'=>400,'msg'=>'参数错误'];
        }else{
            $check = (new Commons())->checkParameter($detail,[
                'old_purchase_code|原单据编号'=>'require',
                'purchase_code|单据编号'=>'require',
                'purchase_time|单据时间'=>'require',
                'business_type|单据类型'=>'require|in:1,2,3,4,5',
                'account_list|详细信息'=>'require',
            ]);
            if(isset($check['status'])){
                return $check;
            }else{
                $adminId = (new Commons())->getAdminId();
                if(empty($adminId)){
                    return ['status'=>410,'msg'=>'登陆无效，请重新登陆'];
                }
                $status = (new Commons())->checkCode($detail['purchase_code'],23);//验证编号是否合法
                if($status){
                    $model = new Writeoff();
                    $row = $model->where(['purchase_code'=>$detail['old_purchase_code']])->find();
                    if(empty($row)){
                        return ['status'=>500,'msg'=>'修改的单据不存在'];
                    }
                    $old_purchase_code = $detail['old_purchase_code'];
                    $examine= (new Commons())->getSet('examine','is_checked');

                    $account_list = isset($detail['account_list'])?$detail['account_list']:'';
                    $account = (array)json_decode($account_list, true);
                    $sale_list = isset($detail['sale_list'])?$detail['sale_list']:'';
                    $sale = (array)json_decode($sale_list, true);

                    $business_type = $detail['business_type'];
                    $info = [];
                    $log_arr = [];
                    $log_add = [];
                    $order_id = [];
                    foreach ($account as $account_k=>$account_v){
                        if(!empty($account_v['purchase_numbers']) && !empty($account_v['purchase_type'])){
                            $order = Db::name('kuyou_writeoff_source')->where(['id'=>$account_v['purchase_type']])->find();
                            if(empty($order)){
                                return ['status'=>500,'msg'=>'源单信息查询错误'];
                            }
                            if(in_array($account_v['purchase_numbers'],$order_id)){
                                return ['status'=>500,'msg'=>'不可多次选择相同的源单'];
                            }else{
                                $order_id[] = $account_v['purchase_numbers'];
                            }
                            $thisrow = [
                                'source_id'        => $order['id'],
                                'purchase_code'    => $detail['purchase_code'],
                                'purchase_time'    => strtotime($detail['purchase_time']),
                                'type'             => $order['type'],
                                'purchase_number'  => $order['purchase_code'],
                                'business_type'    => $business_type,
                                'business_name'    => isset($account_v['business_type'])?$account_v['business_type']:null,
                                'purchase_type'    => $order['purchase_type'],
                                'times'            => $order['purchase_time'],
                                'money'            => $order['price'],
                                'write_off'        => isset($account_v['write_off'])?(float)$account_v['write_off']:0,
                                'write_off_money'  => isset($account_v['write_off_money'])?(float)$account_v['write_off_money']:0,
                                'write_off_price'  => isset($account_v['write_off_price'])?(float)$account_v['write_off_price']:0,
                                'top'              => 1,
                            ];
                            $info[] = $thisrow;

                            $where = [];
                            $where['source_id'] = $order['id'];
                            $log = Db::name('kuyou_writeoff_log')->where($where)->find();
                            if($log){
                                $status = true;
                                foreach ($log_arr as $log_arr_k=>$log_arr_v){
                                    if($log_arr_v['id']==$log['id']){
                                        $status = false;
                                        $log_arr[$log_arr_k]['money'] += $thisrow['write_off_price'];
                                        $log_arr[$log_arr_k]['write_off'] -= $thisrow['write_off_price'];
                                    }
                                }
                                if($status){
                                    $log_arr[] = [
                                        'id' => $log['id'],
                                        'write_off' => $log['write_off']-$thisrow['write_off_price'],
                                        'money' => $log['money']+$thisrow['write_off_price'],
                                    ];
                                }
                            }else{
                                $log_add[] = [
                                    'source_id' => $order['id'],
                                    'write_off' => $thisrow['write_off_money']-$thisrow['write_off_price'],
                                    'money' => $thisrow['write_off_price'],
                                ];
                            }
                        }
                    }

                    $account_money = 0;
                    foreach ($info as $info_k=>$info_v){
                        $account_money += $info_v['write_off_price'];
                    }

                    $order_id = [];
                    $sale_money = 0;
                    if($business_type<=3){
                        foreach ($sale as $account_k=>$account_v){
                            if(!empty($account_v['purchase_numbers']) && !empty($account_v['purchase_type'])){
                                $sale_money += $account_v['write_off_price'];
                                $order = Db::name('kuyou_writeoff_source')->where(['id'=>$account_v['purchase_type']])->find();
                                if(empty($order)){
                                    return ['status'=>500,'msg'=>'源单信息查询错误'];
                                }
                                if(in_array($account_v['purchase_numbers'],$order_id)){
                                    return ['status'=>500,'msg'=>'不可多次选择相同的源单'];
                                }else{
                                    $order_id[] = $account_v['purchase_numbers'];
                                }
                                $thisrow = [
                                    'source_id'        => $order['id'],
                                    'purchase_code'    => $detail['purchase_code'],
                                    'purchase_time'    => strtotime($detail['purchase_time']),
                                    'type'             => $order['type'],
                                    'purchase_number'  => $order['purchase_code'],
                                    'business_type'    => $business_type,
                                    'business_name'    => isset($account_v['business_type'])?$account_v['business_type']:null,
                                    'purchase_type'    => $order['purchase_type'],
                                    'times'            => $order['purchase_time'],
                                    'money'            => $order['price'],
                                    'write_off'        => isset($account_v['write_off'])?(float)$account_v['write_off']:0,
                                    'write_off_money'  => isset($account_v['write_off_money'])?(float)$account_v['write_off_money']:0,
                                    'write_off_price'  => isset($account_v['write_off_price'])?(float)$account_v['write_off_price']:0,
                                    'top'              => 2,
                                ];
                                $info[] = $thisrow;

                                $where = [];
                                $where['source_id'] = $order['id'];
                                $log = Db::name('kuyou_writeoff_log')->where($where)->find();
                                if($log){
                                    $status = true;
                                    foreach ($log_arr as $log_arr_k=>$log_arr_v){
                                        if($log_arr_v['id']==$log['id']){
                                            $status = false;
                                            $log_arr[$log_arr_k]['money'] += $thisrow['write_off_price'];
                                            $log_arr[$log_arr_k]['write_off'] -= $thisrow['write_off_price'];
                                        }
                                    }
                                    if($status){
                                        $log_arr[] = [
                                            'id' => $log['id'],
                                            'write_off' => $log['write_off']-$thisrow['write_off_price'],
                                            'money' => $log['money']+$thisrow['write_off_price'],
                                        ];
                                    }
                                }else{
                                    $log_add[] = [
                                        'source_id' => $order['id'],
                                        'write_off' => $thisrow['write_off_money']-$thisrow['write_off_price'],
                                        'money' => $thisrow['write_off_price'],
                                    ];
                                }
                            }
                        }
                    }

                    $rowdata = [
                        'purchase_code'     =>  $detail['purchase_code'],
                        'purchase_time'     =>  strtotime($detail['purchase_time']),
                        'business_type'     =>  $detail['business_type'],
                        'customers_id'      =>  isset($detail['customers_id'])?(float)$detail['customers_id']:null,
                        'customers_out_id'  =>  isset($detail['customers_out_id'])?(float)$detail['customers_out_id']:null,
                        'customers_enter_id'=>  isset($detail['customers_enter_id'])?(float)$detail['customers_enter_id']:null,
                        'suppliers_id'      =>  isset($detail['suppliers_id'])?(float)$detail['suppliers_id']:null,
                        'suppliers_out_id'  =>  isset($detail['suppliers_out_id'])?(float)$detail['suppliers_out_id']:null,
                        'suppliers_enter_id'=>  isset($detail['suppliers_enter_id'])?(float)$detail['suppliers_enter_id']:null,
                        'write_off'         =>  $account_money,
                        'remarks'           =>  $detail['remarks'],
                        'preparation_id'    =>  $adminId,
                        'operation_id'      =>  $adminId,
                        'createtime'        =>  time(),
                        'updatetime'        =>  time(),
                    ];

                    if($account_money!=$sale_money && $business_type<=3){
                        return ['status'=>500,'msg'=>'核销金额错误'];
                    }

                    if($detail['purchase_code']!=$detail['old_purchase_code']){
                        $purchase_id = $model->where(['purchase_code'=>$detail['purchase_code']])->value('id');
                        if($purchase_id){
                            return ['status'=>500,'msg'=>'单据编号已使用，请重新输入单据编号'];
                        }
                    }

                    //详情
                    $info_list = Db::name('kuyou_writeoff_info')->where(['collection_id'=>$row['id']])->select();

                    $writeoff_log = [];
                    foreach ($info_list as $info_list_k=>$info_list_v){
                        $log = Db::name('kuyou_writeoff_log')->where(['source_id'=>$info_list_v['source_id']])->find();
                        if($log){
                            $addstatus = true;
                            foreach ($writeoff_log as $writeoff_log_k=>$writeoff_log_v){
                                if($writeoff_log_v['id']==$log['id']){
                                    $addstatus = false;
                                    $writeoff_log[$writeoff_log_k]['write_off'] = $writeoff_log_v['write_off']+$info_list_v['write_off_price'];
                                    $writeoff_log[$writeoff_log_k]['money'] = $writeoff_log_v['money']-$info_list_v['money'];
                                }
                            }
                            if($addstatus){
                                $writeoff_log[] = [
                                    'id' => $log['id'],
                                    'write_off'=>($log['write_off']+$info_list_v['write_off_price']),
                                    'money'=>($log['money']-$info_list_v['write_off_price'])
                                ];
                            }
                        }
                    }
                    foreach ($log_arr as $log_arr_k=>$log_arr_v){
                        $log = Db::name('kuyou_writeoff_log')->where(['id'=>$log_arr_v['id']])->find();
                        if($log){
                            $addstatus = true;
                            foreach ($writeoff_log as $writeoff_log_k=>$writeoff_log_v){
                                if($writeoff_log_v['id']==$log['id']){
                                    $addstatus = false;
                                    $writeoff_log[$writeoff_log_k]['write_off'] = $writeoff_log_v['write_off']-$log_arr_v['write_off'];
                                    $writeoff_log[$writeoff_log_k]['money'] = $writeoff_log_v['money']+$log_arr_v['money'];
                                }
                            }
                            if($addstatus){
                                $writeoff_log[] = [
                                    'id' => $log['id'],
                                    'write_off'=>($log['write_off']-$log_arr_v['write_off']),
                                    'money'=>($log['money']+$log_arr_v['write_off'])
                                ];
                            }
                        }
                    }

                    if($row){
                        $res = false;
                        Db::startTrans();
                        try {
                            if($examine!=1 && $row['examine_status']==1){
                                self::examinef($detail['old_purchase_code']);
                            }
                            $rowdata['updatetime'] = time();
                            $res = $model->where(['purchase_code'=>$detail['old_purchase_code']])->update($rowdata);

                            if(!empty($writeoff_log)){
                                (new WriteoffLog())->saveAll($writeoff_log);
                            }
                            Db::name('kuyou_writeoff_info')->where(['collection_id'=>$row['id']])->delete();
                            foreach ($info as $info_k=>$info_v){
                                $info[$info_k]['collection_id'] = $row['id'];
                            }
                            Db::name('kuyou_writeoff_info')->insertAll($info);
                            if(!empty($log_add)){
                                (new WriteoffLog())->insertAll($log_add);
                            }
                            Db::commit();
                        } catch (Exception $e) {
                            Db::rollback();
                            return ['status'=>500,'msg'=>$e->getMessage()];
                        }
                        if($res){
                            if($examine!=1){
                                try {
                                    $exa = self::examine($detail['purchase_code']);
                                } catch (Exception $e) {
                                }
                                if(!isset($exa['status']) || (isset($exa['status']) && $exa['status']!=1)){
                                    return ['status'=>500,'msg'=>$exa['msg']];
                                }
                            }
                            return ['status'=>200,'msg'=>'更新成功'];
                        }else{
                            return ['status'=>500,'msg'=>'更新失败'];
                        }
                    }else{
                        return ['status'=>500,'msg'=>'未查询到可更新数据'];
                    }
                }else{
                    return ['status'=>500,'msg'=>'编号规则错误'];
                }
            }
        }
    }

    /**
     * 删除
     * @param string $purchase_code
     * @return array
     */
    public static function delDetail($purchase_code){
        if(empty($purchase_code)){
            return ['status'=>400,'msg'=>'参数错误'];
        }else{
            $purchase_code = explode(',',$purchase_code);
            $model = new Writeoff;
            $examine= (new Commons())->getSet('examine','is_checked');

            $list = $model->where(['purchase_code'=>['in',$purchase_code]])->select();
            $del_id = [];
            foreach ($list as $list_k=>$list_v){
                if($list_v['examine_status']==1 && $examine==1){
                    return ['status'=>500,'msg'=>'不能删除已审核的数据'];
                }else{
                    $del_id[] = $list_v['id'];
                }
            }
            $info_list = Db::name('kuyou_writeoff_info')->where(['collection_id'=>['in',$del_id]])->select();

            $count = 0;
            $res = false;
            Db::startTrans();
            try {
                foreach ($list as $k => $v) {
                    if ($v['examine_status']==1 && $examine!=1){
                        try {
                            self::examinef($v['purchase_code']);
                        } catch (Exception $e) {
                        }
                    }
                    $res = $model->where(['purchase_code'=>$v['purchase_code']])->delete();
                    $count += $res;
                }
                foreach ($info_list as $info_list_k=>$info_list_v){
                    $log = Db::name('kuyou_writeoff_log')->where(['source_id'=>$info_list_v['source_id']])->find();
                    if($log){
                        Db::name('kuyou_writeoff_log')->where(['id'=>$log['id']])->update([
                            'write_off'=>($log['write_off']+$info_list_v['write_off_price']),
                            'money'=>($log['money']-$info_list_v['write_off_price'])
                        ]);
                    }
                }
                foreach ($info_list as $info_list_k=>$info_list_v){
                    $log = Db::name('kuyou_writeoff_log')->where(['source_id'=>$info_list_v['source_id']])->find();
                    if($log && $log['money']==0){
                        Db::name('kuyou_writeoff_log')->where(['id'=>$log['id']])->delete();
                    }
                }
                Db::name('kuyou_writeoff_info')->where(['collection_id'=>['in',$del_id]])->delete();
                Db::commit();
            } catch (Exception $e) {
                Db::rollback();
                return ['status'=>500,'msg'=>$e->getMessage()];
            }
            if($res){
                return ['status'=>200,'msg'=>$count];
            }else{
                return ['status'=>500,'msg'=>'删除失败'];
            }
        }
    }

    /**
     * 审核
     * @param array $purchase_code
     * @return array
     */
    public static function examine($purchase_code = null){
        if(empty($purchase_code)){
            return ['status'=>400,'msg'=>'请选择要操作的数据'];
        }
        $adminId = (new Commons())->getAdminId();
        if(empty($adminId)){
            return ['status'=>410,'msg'=>'登陆无效，请重新登陆'];
        }
        $model = new Writeoff();
        $list = $model->where(['purchase_code'=>['in',$purchase_code],'examine_status'=>'0'])->select();
        if(empty($list)){
            return ['status'=>500,'msg'=>'请选择需要审核的数据'];
        }

        $success_count = 0;
        foreach ($list as $list_k=>$list_v){

            $info = Db::name('kuyou_writeoff_info')->where(['collection_id'=>$list_v['id']])->select();

            Db::startTrans();
            try {
                foreach ($info as $info_k=>$info_v){
                    if($info_v['purchase_type']==3 && $info_v['type']==1){
                        //销售
                        $order = Db::name('kuyou_goods_sales')->where(['purchase_code'=>$info_v['purchase_number']])->find();
                        $more_money = $order['money_tax_price']-$info_v['write_off_price']-$order['pay_money'];
                        $status = $more_money<=0?1:2;
                        $pay_money = $order['pay_money']+$info_v['write_off_price'];
                        Db::name('kuyou_goods_sales')->where(['purchase_code'=>$info_v['purchase_number']])
                            ->update(['pay_money'=>$pay_money,'pay_status'=>$status]);
                    }else if($info_v['purchase_type']==3 && $info_v['type']==2){
                        //销售退货
                        $order = Db::name('kuyou_goods_sales_exchange')->where(['purchase_code'=>$info_v['purchase_number']])->find();
                        $more_money = $order['money_tax_price']+$info_v['write_off_price']-$order['retreat_money'];
                        $status = $more_money==0?1:2;
                        $pay_money = $order['retreat_money']+(-$info_v['write_off_price']);
                        Db::name('kuyou_goods_sales_exchange')->where(['purchase_code'=>$info_v['purchase_number']])
                            ->update(['retreat_money'=>$pay_money,'retreat_status'=>$status]);
                    }else if($info_v['purchase_type']==4 && $info_v['type']==1){
                        //购货
                        $order = Db::name('kuyou_goods_purchase')->where(['purchase_code'=>$info_v['purchase_number']])->find();
                        $more_money = $order['all_money']+$order['tax_money']-$info_v['write_off_price']-$order['pay_money'];
                        $status = $more_money<=0?1:2;
                        $pay_money = $order['pay_money']+$info_v['write_off_price'];
                        Db::name('kuyou_goods_purchase')->where(['purchase_code'=>$info_v['purchase_number']])
                            ->update(['pay_money'=>$pay_money,'pay_status'=>$status]);
                    }else if($info_v['purchase_type']==4 && $info_v['type']==2){
                        //购货退货
                        $order = Db::name('kuyou_goods_exchange')->where(['purchase_code'=>$info_v['purchase_number']])->find();
                        $more_money = $order['all_money']+$order['tax_money']+$info_v['write_off_price']-$order['retreat_money'];;
                        $status = $more_money==0?1:2;
                        $pay_money = $order['retreat_money']+(-$info_v['write_off_price']);
                        Db::name('kuyou_goods_exchange')->where(['purchase_code'=>$info_v['purchase_number']])
                            ->update(['retreat_money'=>$pay_money,'retreat_status'=>$status]);
                    }

                    $writeoff_source = Db::name('kuyou_writeoff_source')->where(['id'=>$info_v['source_id']])->find();
                    if ($info_v['top']==1){
                        if(($info_v['business_type']==1 && $info_v['type']==3)){
                            Db::name('kuyou_sales_payment_log')->insert([
                                'customers_id'      => $writeoff_source['customers_id'],
                                'bill_time'         => $info_v['purchase_time'],
                                'bill_code'         => $info_v['purchase_number'],
                                'bill_codes'        => $info_v['purchase_code'],
                                'business_type'     => '7',
                                'pay_money'         => $info_v['write_off_price'],
                                'createtime'        => time(),
                            ]);
                        }else if($info_v['business_type']==2 && $info_v['type']==3){
                            Db::name('kuyou_payment_log')->insert([
                                'suppliers_code'    => $writeoff_source['suppliers_code'],
                                'bill_time'         => $info_v['purchase_time'],
                                'bill_code'         => $info_v['purchase_number'],
                                'bill_codes'        => $info_v['purchase_code'],
                                'business_type'     => '7',
                                'pay_money'         => $info_v['write_off_price'],
                                'createtime'        => time(),
                            ]);
                        }else if($info_v['business_type']==3 && $info_v['type']<4){
                            Db::name('kuyou_sales_payment_log')->insert([
                                'customers_id'      => $writeoff_source['customers_id'],
                                'bill_time'         => $info_v['purchase_time'],
                                'bill_code'         => $info_v['purchase_number'],
                                'bill_codes'        => $info_v['purchase_code'],
                                'business_type'     => '7',
                                'pay_money'         => $info_v['write_off_price'],
                                'createtime'        => time(),
                            ]);
                        }else if($info_v['business_type']==4 && $info_v['type']<4){
                            Db::name('kuyou_sales_payment_log')->insert([
                                'customers_id'      => $list_v['customers_out_id'],
                                'bill_time'         => $info_v['purchase_time'],
                                'bill_code'         => $info_v['purchase_number'],
                                'bill_codes'        => $info_v['purchase_code'],
                                'business_type'     => '7',
                                'pay_money'         => -$info_v['write_off_price'],
                                'createtime'        => time(),
                            ]);
                            Db::name('kuyou_sales_payment_log')->insert([
                                'customers_id'      => $list_v['customers_enter_id'],
                                'bill_time'         => $info_v['purchase_time'],
                                'bill_code'         => $info_v['purchase_number'],
                                'bill_codes'        => $info_v['purchase_code'],
                                'business_type'     => '7',
                                'pay_money'         => $info_v['write_off_price'],
                                'createtime'        => time(),
                            ]);
                        }else if($info_v['business_type']==5 && $info_v['type']<4){
                            $suppliers = Db::name('kuyou_suppliers')->where(['id'=>$list_v['suppliers_out_id']])->value('supplyer_code');
                            Db::name('kuyou_payment_log')->insert([
                                'suppliers_code'    => $suppliers,
                                'bill_time'         => $info_v['purchase_time'],
                                'bill_code'         => $info_v['purchase_number'],
                                'bill_codes'        => $info_v['purchase_code'],
                                'business_type'     => '7',
                                'pay_money'         => $info_v['write_off_price'],
                                'createtime'        => time(),
                            ]);
                            $suppliers = Db::name('kuyou_suppliers')->where(['id'=>$list_v['suppliers_enter_id']])->value('supplyer_code');
                            Db::name('kuyou_payment_log')->insert([
                                'suppliers_code'    => $suppliers,
                                'bill_time'         => $info_v['purchase_time'],
                                'bill_code'         => $info_v['purchase_number'],
                                'bill_codes'        => $info_v['purchase_code'],
                                'business_type'     => '7',
                                'pay_money'         => -$info_v['write_off_price'],
                                'createtime'        => time(),
                            ]);
                        }
                    }else if ($info_v['top']==2){
                        if(($info_v['business_type']==1 && ($info_v['purchase_type']==3 || $info_v['purchase_type']==5))){
                            Db::name('kuyou_sales_payment_log')->insert([
                                'customers_id'      => $writeoff_source['customers_id'],
                                'bill_time'         => $info_v['purchase_time'],
                                'bill_code'         => $info_v['purchase_number'],
                                'bill_codes'        => $info_v['purchase_code'],
                                'business_type'     => '7',
                                'pay_money'         => $info_v['write_off_price'],
                                'createtime'        => time(),
                            ]);
                        }else if($info_v['business_type']==2 && ($info_v['purchase_type']==4 || $info_v['purchase_type']==5)){
                            Db::name('kuyou_payment_log')->insert([
                                'suppliers_code'    => $writeoff_source['suppliers_code'],
                                'bill_time'         => $info_v['purchase_time'],
                                'bill_code'         => $info_v['purchase_number'],
                                'bill_codes'        => $info_v['purchase_code'],
                                'business_type'     => '7',
                                'pay_money'         => $info_v['write_off_price'],
                                'createtime'        => time(),
                            ]);
                        }else if($info_v['business_type']==3 && ($info_v['purchase_type']==4 || $info_v['purchase_type']==5)){
                            Db::name('kuyou_payment_log')->insert([
                                'suppliers_code'    => $writeoff_source['suppliers_code'],
                                'bill_time'         => $info_v['purchase_time'],
                                'bill_code'         => $info_v['purchase_number'],
                                'bill_codes'        => $info_v['purchase_code'],
                                'business_type'     => '7',
                                'pay_money'         => $info_v['write_off_price'],
                                'createtime'        => time(),
                            ]);
                        }
                    }

                    if(($info_v['purchase_type']==3 || $info_v['purchase_type']==4) && $info_v['type']==1){
                        Db::name('kuyou_writeoff_info')->where(['id'=>$info_v['id']])->update([
                            'old_money'=>$order['pay_money'],
                            'old_status'=>$order['pay_status'],
                        ]);
                    }else if(($info_v['purchase_type']==3 || $info_v['purchase_type']==4) && $info_v['type']==2){
                        Db::name('kuyou_writeoff_info')->where(['id'=>$info_v['id']])->update([
                            'old_money'=>$order['retreat_money'],
                            'old_status'=>$order['retreat_status'],
                        ]);
                    }
                }

                switch ($list_v['business_type']){
                    case 1:
                        //预收冲应收
                        Db::name('kuyou_accounts_receivable')->insert([
                            'customers_id'      => $list_v['customers_id'],
                            'purchase_time'     => $list_v['purchase_time'],
                            'purchase_code'     => $list_v['purchase_code'],
                            'business_type'     => '1',
                            'receivable'        => -$list_v['write_off'],
                            'advance'           => -$list_v['write_off'],
                            'remark'            => $list_v['remarks'],
                            'receivable_money'  => -$list_v['write_off'],
                            'createtime'        => time(),
                            'updatetime'        => time(),
                        ]);
                        $result = $model->where(['id'=>$list_v['id'],'examine_status'=>'0'])->update(['examine_status'=>1,'examine_id'=>$adminId,'examine_time'=>time(),'operation_id'=>$adminId]);
                        break;
                    case 2:
                        //预付冲应付
                        Db::name('kuyou_accounts_copewith')->insert([
                            'suppliers_id'      => $list_v['suppliers_id'],
                            'purchase_time'     => $list_v['purchase_time'],
                            'purchase_code'     => $list_v['purchase_code'],
                            'business_type'     => '2',
                            'receivable'        => -$list_v['write_off'],
                            'advance'           => -$list_v['write_off'],
                            'remark'            => $list_v['remarks'],
                            'receivable_money'  => -$list_v['write_off'],
                            'createtime'        => time(),
                            'updatetime'        => time(),
                        ]);
                        $result = $model->where(['id'=>$list_v['id'],'examine_status'=>'0'])->update(['examine_status'=>1,'examine_id'=>$adminId,'examine_time'=>time(),'operation_id'=>$adminId]);
                        break;
                    case 3:
                        //应收冲应付
                        Db::name('kuyou_accounts_receivable')->insert([
                            'customers_id'      => $list_v['customers_id'],
                            'purchase_time'     => $list_v['purchase_time'],
                            'purchase_code'     => $list_v['purchase_code'],
                            'business_type'     => '3',
                            'receivable'        => -$list_v['write_off'],
                            'remark'            => $list_v['remarks'],
                            'receivable_money'  => -$list_v['write_off'],
                            'createtime'        => time(),
                            'updatetime'        => time(),
                        ]);
                        Db::name('kuyou_accounts_copewith')->insert([
                            'suppliers_id'      => $list_v['suppliers_id'],
                            'purchase_time'     => $list_v['purchase_time'],
                            'purchase_code'     => $list_v['purchase_code'],
                            'business_type'     => '3',
                            'receivable'        => -$list_v['write_off'],
                            'remark'            => $list_v['remarks'],
                            'receivable_money'  => -$list_v['write_off'],
                            'createtime'        => time(),
                            'updatetime'        => time(),
                        ]);
                        $suppliers = Db::name('kuyou_customers')->where(['id'=>$list_v['customers_id']])->find();
                        $gave_money = $suppliers['need_receive_account'] - $list_v['write_off'];
                        Db::name('kuyou_customers')->where(['id'=>$list_v['customers_id']])->update(['need_receive_account'=>$gave_money]);

                        $suppliers = Db::name('kuyou_suppliers')->where(['id'=>$list_v['suppliers_id']])->find();
                        $gave_money = $suppliers['need_give_account'] - $list_v['write_off'];
                        Db::name('kuyou_suppliers')->where(['id'=>$list_v['suppliers_id']])->update(['need_give_account'=>$gave_money]);

                        $result = $model->where(['id'=>$list_v['id'],'examine_status'=>'0'])->update(['examine_status'=>1,'examine_id'=>$adminId,'examine_time'=>time(),'operation_id'=>$adminId]);
                        break;
                    case 4:
                        //应收转应收
                        Db::name('kuyou_accounts_receivable')->insert([
                            'customers_id'      => $list_v['customers_out_id'],
                            'purchase_time'     => $list_v['purchase_time'],
                            'purchase_code'     => $list_v['purchase_code'],
                            'business_type'     => '4',
                            'receivable'        => -$list_v['write_off'],
                            'remark'            => $list_v['remarks'],
                            'receivable_money'  => -$list_v['write_off'],
                            'createtime'        => time(),
                            'updatetime'        => time(),
                        ]);

                        $suppliers = Db::name('kuyou_customers')->where(['id'=>$list_v['customers_out_id']])->find();
                        $gave_money = $suppliers['need_receive_account'] - $list_v['write_off'];
                        Db::name('kuyou_customers')->where(['id'=>$list_v['customers_out_id']])->update(['need_receive_account'=>$gave_money]);

                        Db::name('kuyou_accounts_receivable')->insert([
                            'customers_id'      => $list_v['customers_enter_id'],
                            'purchase_time'     => $list_v['purchase_time'],
                            'purchase_code'     => $list_v['purchase_code'],
                            'business_type'     => '4',
                            'receivable'        => $list_v['write_off'],
                            'remark'            => $list_v['remarks'],
                            'receivable_money'  => $list_v['write_off'],
                            'createtime'        => time(),
                            'updatetime'        => time(),
                        ]);

                        $suppliers = Db::name('kuyou_customers')->where(['id'=>$list_v['customers_enter_id']])->find();
                        $gave_money = $suppliers['need_receive_account'] + $list_v['write_off'];
                        Db::name('kuyou_customers')->where(['id'=>$list_v['customers_enter_id']])->update(['need_receive_account'=>$gave_money]);

                        Db::name('kuyou_writeoff_source')->insert([
                            'purchase_type' => 3,
                            'type' => 4,
                            'customers_id' => $list_v['customers_enter_id'],
                            'purchase_code' => $list_v['purchase_code'],
                            'purchase_time' => $list_v['purchase_time'],
                            'price' => $list_v['write_off'],
                            'money' => 0,
                            'write_off' => $list_v['write_off'],
                        ]);
                        $result = $model->where(['id'=>$list_v['id'],'examine_status'=>'0'])->update(['examine_status'=>1,'examine_id'=>$adminId,'examine_time'=>time(),'operation_id'=>$adminId]);
                        break;
                    case 5:
                        //应付转应付
                        Db::name('kuyou_accounts_copewith')->insert([
                            'suppliers_id'      => $list_v['suppliers_out_id'],
                            'purchase_time'     => $list_v['purchase_time'],
                            'purchase_code'     => $list_v['purchase_code'],
                            'business_type'     => '5',
                            'receivable'        => -$list_v['write_off'],
                            'remark'            => $list_v['remarks'],
                            'receivable_money'  => -$list_v['write_off'],
                            'createtime'        => time(),
                            'updatetime'        => time(),
                        ]);

                        $suppliers = Db::name('kuyou_suppliers')->where(['id'=>$list_v['suppliers_out_id']])->find();
                        $gave_money = $suppliers['need_give_account'] - $list_v['write_off'];
                        Db::name('kuyou_suppliers')->where(['id'=>$list_v['suppliers_out_id']])->update(['need_give_account'=>$gave_money]);

                        Db::name('kuyou_accounts_copewith')->insert([
                            'suppliers_id'      => $list_v['suppliers_enter_id'],
                            'purchase_time'     => $list_v['purchase_time'],
                            'purchase_code'     => $list_v['purchase_code'],
                            'business_type'     => '5',
                            'receivable'        => $list_v['write_off'],
                            'remark'            => $list_v['remarks'],
                            'receivable_money'  => $list_v['write_off'],
                            'createtime'        => time(),
                            'updatetime'        => time(),
                        ]);

                        $suppliers = Db::name('kuyou_suppliers')->where(['id'=>$list_v['suppliers_enter_id']])->find();
                        $gave_money = $suppliers['need_give_account'] + $list_v['write_off'];
                        Db::name('kuyou_suppliers')->where(['id'=>$list_v['suppliers_enter_id']])->update(['need_give_account'=>$gave_money]);

                        $suppliers = Db::name('kuyou_suppliers')->where(['id'=>$list_v['suppliers_enter_id']])->value('supplyer_code');
                        Db::name('kuyou_writeoff_source')->insert([
                            'purchase_type' => 4,
                            'type' => 4,
                            'suppliers_code' => $suppliers,
                            'purchase_code' => $list_v['purchase_code'],
                            'purchase_time' => $list_v['purchase_time'],
                            'price' => $list_v['write_off'],
                            'money' => 0,
                            'write_off' => $list_v['write_off'],
                        ]);
                        $result = $model->where(['id'=>$list_v['id'],'examine_status'=>'0'])->update(['examine_status'=>1,'examine_id'=>$adminId,'examine_time'=>time(),'operation_id'=>$adminId]);
                        break;
                }
                Db::commit();
            } catch (Exception $e) {
                Db::rollback();
                return ['status'=>500,'msg'=>$e->getMessage()];
            }
            if(isset($result) && $result !== false){
                $success_count += 1;
            }
        }
        if($success_count>0){
            return ['status'=>1,'msg'=>sizeof($list)];
        }else{
            return ['status'=>500,'msg'=>'审核失败'];
        }
    }

    /**
     * 反审核
     * @param array $purchase_code
     * @return array
     */
    public static function examinef($purchase_code = null){
        if(empty($purchase_code)){
            return ['status'=>400,'msg'=>'请选择要操作的数据'];
        }
        $adminId = (new Commons())->getAdminId();
        if(empty($adminId)){
            return ['status'=>410,'msg'=>'登陆无效，请重新登陆'];
        }

        $model = new Writeoff();
        $list = $model->where(['purchase_code'=>['in',$purchase_code],'examine_status'=>'1'])->select();
        if(empty($list)){
            return ['status'=>500,'msg'=>'请选择需要反审核的数据'];
        }
        $success_count = 0;
        foreach ($list as $list_k=>$list_v){

            $info = Db::name('kuyou_writeoff_info')->where(['collection_id'=>$list_v['id']])->select();

            Db::startTrans();
            try {
                foreach ($info as $info_k=>$info_v){
                    if($info_v['purchase_type']==3 && $info_v['type']==1){
                        //销售
                        $order = Db::name('kuyou_goods_sales')->where(['purchase_code'=>$info_v['purchase_number']])->find();
                        if($order){
                            Db::name('kuyou_goods_sales')->where(['purchase_code'=>$info_v['purchase_number']])
                                ->update(['pay_money'=>$info_v['old_money'],'pay_status'=>$info_v['old_status']]);
                        }
                    }else if($info_v['purchase_type']==3 && $info_v['type']==2){
                        //销售退货
                        $order = Db::name('kuyou_goods_sales_exchange')->where(['purchase_code'=>$info_v['purchase_number']])->find();
                        if($order){
                            Db::name('kuyou_goods_sales_exchange')->where(['purchase_code'=>$info_v['purchase_number']])
                                ->update(['retreat_money'=>$info_v['old_money'],'retreat_status'=>$info_v['old_status']]);
                        }
                    }else if($info_v['purchase_type']==4 && $info_v['type']==1){
                        //购货
                        $order = Db::name('kuyou_goods_purchase')->where(['purchase_code'=>$info_v['purchase_number']])->find();
                        if($order){
                            Db::name('kuyou_goods_purchase')->where(['purchase_code'=>$info_v['purchase_number']])
                                ->update(['pay_money'=>$info_v['old_money'],'pay_status'=>$info_v['old_status']]);
                        }
                    }else if($info_v['purchase_type']==4 && $info_v['type']==2){
                        //购货退货
                        $order = Db::name('kuyou_goods_exchange')->where(['purchase_code'=>$info_v['purchase_number']])->find();
                        if($order){
                            Db::name('kuyou_goods_exchange')->where(['purchase_code'=>$info_v['purchase_number']])
                                ->update(['retreat_money'=>$info_v['old_money'],'retreat_status'=>$info_v['old_status']]);
                        }
                    }

                    Db::name('kuyou_payment_log')->where(['bill_codes'=>$info_v['purchase_code']])->delete();
                    Db::name('kuyou_sales_payment_log')->where(['bill_codes'=>$info_v['purchase_code']])->delete();
                }

                switch ($list_v['business_type']){
                    case 1:
                        //预收冲应收
                        Db::name('kuyou_accounts_receivable')->where(['business_type'=>'1','purchase_code'=>$list_v['purchase_code']])->delete();
                        $result = $model->where(['id'=>$list_v['id'],'examine_status'=>'1'])->update(['examine_status'=>'0','examine_id'=>null,'examine_time'=>null,'operation_id'=>$adminId]);
                        break;
                    case 2:
                        //预付冲应付
                        Db::name('kuyou_accounts_copewith')->where(['business_type'=>'2','purchase_code'=>$list_v['purchase_code']])->delete();
                        $result = $model->where(['id'=>$list_v['id'],'examine_status'=>'1'])->update(['examine_status'=>'0','examine_id'=>null,'examine_time'=>null,'operation_id'=>$adminId]);
                        break;
                    case 3:
                        //应收冲应付
                        $suppliers = Db::name('kuyou_customers')->where(['id'=>$list_v['customers_id']])->find();
                        $gave_money = $suppliers['need_receive_account'] + $list_v['write_off'];
                        Db::name('kuyou_customers')->where(['id'=>$list_v['customers_id']])->update(['need_receive_account'=>$gave_money]);

                        $suppliers = Db::name('kuyou_suppliers')->where(['id'=>$list_v['suppliers_id']])->find();
                        $gave_money = $suppliers['need_give_account'] + $list_v['write_off'];
                        Db::name('kuyou_suppliers')->where(['id'=>$list_v['suppliers_id']])->update(['need_give_account'=>$gave_money]);

                        Db::name('kuyou_accounts_receivable')->where(['business_type'=>'3','purchase_code'=>$list_v['purchase_code']])->delete();
                        Db::name('kuyou_accounts_copewith')->where(['business_type'=>'3','purchase_code'=>$list_v['purchase_code']])->delete();
                        $result = $model->where(['id'=>$list_v['id'],'examine_status'=>'1'])->update(['examine_status'=>'0','examine_id'=>null,'examine_time'=>null,'operation_id'=>$adminId]);
                        break;
                    case 4:
                        //应收转应收

                        $suppliers = Db::name('kuyou_customers')->where(['id'=>$list_v['customers_out_id']])->find();
                        $gave_money = $suppliers['need_receive_account'] + $list_v['write_off'];
                        Db::name('kuyou_customers')->where(['id'=>$list_v['customers_out_id']])->update(['need_receive_account'=>$gave_money]);

                        $suppliers = Db::name('kuyou_customers')->where(['id'=>$list_v['customers_enter_id']])->find();
                        $gave_money = $suppliers['need_receive_account'] - $list_v['write_off'];
                        Db::name('kuyou_customers')->where(['id'=>$list_v['customers_enter_id']])->update(['need_receive_account'=>$gave_money]);

                        Db::name('kuyou_writeoff_source')->where(['purchase_code'=>$list_v['purchase_code'],'type'=>4])->delete();
                        Db::name('kuyou_accounts_receivable')->where(['business_type'=>'4','purchase_code'=>$list_v['purchase_code']])->delete();
                        $result = $model->where(['id'=>$list_v['id'],'examine_status'=>'1'])->update(['examine_status'=>'0','examine_id'=>null,'examine_time'=>null,'operation_id'=>$adminId]);
                        break;
                    case 5:
                        //应付转应付

                        $suppliers = Db::name('kuyou_suppliers')->where(['id'=>$list_v['suppliers_out_id']])->find();
                        $gave_money = $suppliers['need_give_account'] + $list_v['write_off'];
                        Db::name('kuyou_suppliers')->where(['id'=>$list_v['suppliers_out_id']])->update(['need_give_account'=>$gave_money]);

                        $suppliers = Db::name('kuyou_suppliers')->where(['id'=>$list_v['suppliers_enter_id']])->find();
                        $gave_money = $suppliers['need_give_account'] - $list_v['write_off'];
                        Db::name('kuyou_suppliers')->where(['id'=>$list_v['suppliers_enter_id']])->update(['need_give_account'=>$gave_money]);

                        Db::name('kuyou_writeoff_source')->where(['purchase_code'=>$list_v['purchase_code'],'type'=>4])->delete();
                        Db::name('kuyou_accounts_copewith')->where(['business_type'=>'5','purchase_code'=>$list_v['purchase_code']])->delete();
                        $result = $model->where(['id'=>$list_v['id'],'examine_status'=>'1'])->update(['examine_status'=>'0','examine_id'=>null,'examine_time'=>null,'operation_id'=>$adminId]);
                        break;
                }
                Db::commit();
            } catch (Exception $e) {
                Db::rollback();
                return ['status'=>500,'msg'=>$e->getMessage()];
            }
            if(isset($result) && $result !== false){
                $success_count += 1;
            }
        }
        if($success_count>0){
            return ['status'=>1,'msg'=>sizeof($list)];
        }else{
            return ['status'=>500,'msg'=>'审核失败'];
        }
    }

}
